package com.teamventure.app.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

public class Connect {
	
	private String url = "http://www.team-venture.uphero.com/api.php";
	private Connection conn = null;
	
	public Connect() {
	}
	
	public boolean isConnected() {
		boolean connected = false;
		try {
			if(this.conn != null) {
				connected = this.conn.isClosed();
			}
		} catch(SQLException e) {
			
		}
		return connected;
	}
	
	public String sendRequest(String request, Map<String,String> parameters){
		StringBuilder sb = new StringBuilder();
		sb.append(url);
		sb.append("?function=");
		sb.append(request);
		for(String s : parameters.keySet()) {
			sb.append('&');
			sb.append(s);
			sb.append('=');
			sb.append(parameters.get(s));
		}
		
	    URL myurl;
	    BufferedReader in = null;
	    StringBuilder response = new StringBuilder();
	    
		try {
			myurl = new URL(sb.toString());
			HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
			con.setRequestMethod("GET");
			
			con.setUseCaches(false);
			con.setDoInput(true);
			con.setDoOutput(true);
			
		    InputStream ins = con.getInputStream();
		    InputStreamReader isr = new InputStreamReader(ins);
		    in = new BufferedReader(isr);
		    
		    String inputLine="";
		    
		    while ((inputLine = in.readLine()) != null)
		    {
		    	response.append(inputLine);
		    	response.append("\n");
		    }
		    
		} catch (MalformedURLException e) {
			// TODO Do something with the caught MalformedURLException (maybe)
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Do something with the caught IOException (maybe)
			e.printStackTrace();
		}finally{
			try {
				if(in != null) {
					in.close();
				}
			} catch (IOException e) {
				// TODO Do something with the caught IOException (maybe)
			}
		}
	    
		//Get rid of all the crap at the end of the response
		String edited = response.substring(0, response.indexOf("<!--")-1);
		
		return edited;
	}
	
	public void close() {
		try {
			conn.close();
		} catch (SQLException e) {
			
		}
	}
}
